/*
 Copyright (c) 2007 AppScrapper authors and contributors
 
 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:
 
 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */

#import "TDProtectionController.h"

@implementation TDProtectionController

TDProtectionController *sharedProtectionInstance = nil;

+ (TDProtectionController *) protectionController
{
    if (!sharedProtectionInstance)
        sharedProtectionInstance = [[self alloc] init];
    return sharedProtectionInstance;
}

- (id) init
{
    if (sharedProtectionInstance)
        return sharedProtectionInstance;
    
    if ((self = [super init]))
        protectedApps = [[NSMutableArray alloc] init];
    
    return self;
}

- (void) controllerDidLoad
{
    defaults = [NSUserDefaults standardUserDefaults];
    [self setProtectedApps:[[defaults arrayForKey:@"protectedAppsList"] mutableCopy]];
    
    [self addObserver:self 
           forKeyPath:@"protectedApps" 
              options:0 
              context:nil];
}

- (void) observeValueForKeyPath: (NSString *) keyPath
                       ofObject: (id) object
                         change: (NSDictionary *) change
                        context: (void *) context
{
    [defaults setObject:protectedApps forKey:@"protectedAppsList"];
}

- (BOOL) isProtected:(NSMutableDictionary *)protectionEntry
{
    if ([protectedApps containsObject:protectionEntry])
        return YES;
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    if ([defaults boolForKey:@"protectOpenApps"]) {
        NSString *bundleIdentifier = [protectionEntry objectForKey:@"bundleIdentifier"];
        NSDictionary *dict;
        NSEnumerator *enumerator = [[[NSWorkspace sharedWorkspace] launchedApplications] objectEnumerator];
        
        while ((dict = [enumerator nextObject])) {
            if ([[dict objectForKey: @"NSApplicationBundleIdentifier"] isEqualToString: bundleIdentifier]) {
                [pool release];
                return YES;
            }
        }
    }
    
    if ([defaults boolForKey:@"protectDockedApps"]) {
        NSString *bundleIdentifier = [protectionEntry objectForKey:@"bundleIdentifier"],
                 *dockPath = [@"~/Library/Preferences/com.apple.dock.plist" stringByExpandingTildeInPath];
        NSDictionary *dockDict = [NSDictionary dictionaryWithContentsOfFile: dockPath],
                     *dict;
        NSEnumerator *enumerator = [[dockDict objectForKey:@"persistent-apps"] objectEnumerator];
        while ((dict = [enumerator nextObject])) {
            NSString *appPath = [[[dict objectForKey:@"tile-data"] objectForKey:@"file-data"] objectForKey:@"_CFURLString"];
            if ([[protectionEntry objectForKey:@"path"] isEqualToString: appPath] ||
                [[[self protectionEntryWithPath:appPath] objectForKey:@"bundleIdentifier"] isEqualToString:bundleIdentifier]) {
                [pool release];
                return YES;
            }
        }
    }
    
    if ([defaults boolForKey:@"protectDefaultApps"]) {
        if ([[protectionEntry objectForKey:@"bundleIdentifier"] hasPrefix:APPLE_BUNDLE_IDENTIFIER_PREFIX]) {
            [pool release];
            return YES;
        }
    }
    
    [pool release];
    return NO;
}

- (NSMutableDictionary *) protectionEntryWithPath:(NSString *)path
{
    NSString *appPlistPath = [path stringByAppendingPathComponent:@"Contents/Info.plist"];
    NSDictionary *appPlist = [NSDictionary dictionaryWithContentsOfFile:appPlistPath];
    NSLog(@"%@", [appPlist objectForKey:@"CFBundleIdentifier"]);
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:path, @"path", 
                [appPlist objectForKey:@"CFBundleIdentifier"], @"bundleIdentifier", nil];
}

- (void) addApp:(NSMutableDictionary *)protectionEntry
{
    NSRange range = NSMakeRange([protectedApps count], 1);
    NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:range];
    
    [self willChange:NSKeyValueChangeInsertion valuesAtIndexes:indexes
              forKey:@"protectedApps"];
    [protectedApps addObject:protectionEntry];
    [self didChange:NSKeyValueChangeInsertion valuesAtIndexes:indexes
             forKey:@"protectedApps"];
    /* [tableView_protected reloadData]; */
}

- (void)removeApp:(NSMutableDictionary *)protectionEntry 
{

}

#pragma mark Accessors
- (unsigned int) countOfProtectedApps
{
    return [protectedApps count];
}

- (NSMutableArray *)protectedApps
{
    return protectedApps;
}

- (void) setProtectedApps:(NSMutableArray *)newArray
{
    if (protectedApps != newArray)
    {
        if (protectedApps)
            [protectedApps autorelease];
        protectedApps = [newArray retain];
    }
}

#pragma mark TableView (unused)
/* Keep it in here in case bindings fall short for some future use

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    return [protectedApps count];
}

- (id)tableView:(NSTableView *)table objectValueForTableColumn:(NSTableColumn *)column row:(int)row
{
    NSString *key = [column identifier];
    NSLog(key);
    NSMutableDictionary *d = [protectedApps objectAtIndex:row];
    if ([key isEqualToString:@"image"]) {
        NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:[[d objectForKey:@"path"] stringByExpandingTildeInPath]];
        [icon setScalesWhenResized: YES];
        [icon setSize: NSMakeSize(16.0, 16.0)];
        return icon;
    } else if ([key isEqualToString:@"name"])
        return [[[d objectForKey:@"path"] lastPathComponent] stringByDeletingPathExtension];
    return [d objectForKey:key];
}*/

@end
